//
//  Fraction.m
//  02-Fraction
//
//  Created by mafeng on 16/7/6.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction
- (instancetype)initWithnumberator:(NSInteger)numberator
                       denominator:(NSInteger)denominator {
    self = [super init];
    if (self) {
        if (denominator == 0) {
            NSLog(@"分母不能为0");
            exit(1);
        }
        _numberator = numberator;
        _denominator = denominator;
    }
    return  self;
}
+ (instancetype)fractionWithnumberator:(NSInteger)numberator
                           denominator:(NSInteger)denominator {
    Fraction *fraction = [[[Fraction alloc] initWithnumberator:numberator denominator:denominator] autorelease];
    return fraction;
}
- (Fraction *)addfraction:(Fraction *)fraction {
    NSInteger a = self.denominator * fraction.denominator;
    NSInteger b = self.numberator * fraction.denominator + fraction.numberator * self.denominator;
    return [Fraction fractionWithnumberator:a denominator:b];
}
- (Fraction *)multiplyfraction:(Fraction *)fraction {
    NSInteger a = self.denominator * fraction.denominator;
    NSInteger b = self.numberator * fraction.numberator;
    return [Fraction fractionWithnumberator:b denominator:a];
}
- (Fraction *)reductfraction {
    NSInteger a = self.numberator;
    NSInteger b = self.denominator;
    NSInteger c;
    // 辗转相除法
    do {
        c = a % b;
        a = b;
        b = c;
    } while (c == 0);
    NSInteger d = self.numberator / b;
    NSInteger f = self.denominator / b;
    return [Fraction fractionWithnumberator:d denominator:f];
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"%ld/%ld", self.numberator, self.denominator];
}
@end
